package com.jsits.v2x.fs8.server;

import com.jsits.v2x.common.dto.ControlDto;
import com.jsits.v2x.common.enums.DevicePosition;
import com.jsits.v2x.common.enums.NumberColor;
import com.jsits.v2x.fs8.config.Fs8Config;
import java.awt.*;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class Fs8SocketServer implements Runnable {
	public static Fs8Config fs8Config;

	// 屏幕位置--显示内容
	private static Map<DevicePosition,String> socketMap = new HashMap<DevicePosition,String>();
	// 屏幕位置--显示内容 上一次
	private static Map<DevicePosition,String> lastMap = new HashMap<DevicePosition,String>();

	// 屏幕位置--socket连接
	private static Map<DevicePosition,Socket> socketCache = new HashMap<DevicePosition,Socket>();
	
	private static ServerSocket server = null; 
	
	public static void init() {
		try{
			server = new ServerSocket(fs8Config.getServerPort());
			System.out.println("socket服务开始");
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		 while (true) {
             System.out.println("Listenning...");  
             try {
//               每个请求交给一个线程去处理  
            	 Socket sc = server.accept();  
                
            	 String ip = sc.getInetAddress().toString().substring(1);
					
				System.out.println("客户端ip地址是：" + ip + new Date());
				System.out.println("客户端端口号是：" + sc.getPort());

				if(ip.equals(fs8Config.getMainLed1())) {
					socketCache.put(DevicePosition.DEVICE_POSITION_MAIN_1, sc);
				} else if(ip.equals(fs8Config.getMainLed2())) {
					socketCache.put(DevicePosition.DEVICE_POSITION_MAIN_2, sc);
				}
					
            	Thread.sleep(1000); 
             } catch (Exception e) {
                 e.printStackTrace();  
             }
         }
	}

	/**
	 * 向八字屏发送控制信息
	 * @param controlDto 屏幕显示信息
	 */
	
	public static void sendCtrontrolData(ControlDto controlDto) {
		// 首先判断该位置是否有屏幕需要控制
		if((controlDto.getDevicePosition().equals(DevicePosition.DEVICE_POSITION_MAIN_1) && fs8Config.getHasMain1() > 0)
				|| (controlDto.getDevicePosition().equals(DevicePosition.DEVICE_POSITION_MAIN_2) && fs8Config.getHasMain2() > 0)) {

			DevicePosition devicePosition = controlDto.getDevicePosition();
			Socket sc = socketCache.get(devicePosition);
			if(sc == null) {
				return;
			}

			socketMap.put(devicePosition, getContent(controlDto));
			String content = socketMap.get(devicePosition);
			if (content == null) {
				content = "2000";
			}
			if (lastMap.get(devicePosition) == null) {
				// 如果是第一次
				lastMap.put(devicePosition, content);
			}
			// 如果和上一次发的不相等
			if (!lastMap.get(devicePosition).equals(content)) {
				try {
					writeMsgToClient(sc.getOutputStream(), content);
					System.out.println(devicePosition + ":" + content + "发送成功" + new Date());
				} catch (IOException e) {
					e.printStackTrace();
				}
				lastMap.put(devicePosition, content);
			}
		}
	}
	
	private static void writeMsgToClient(OutputStream outputStream, String string) throws IOException {  
        Writer writer = new OutputStreamWriter(outputStream);  
        writer.append(string);  
        writer.flush();  
//        writer.close(); 
    }

	@Override
	public void run() {
		init();
	}
	
	private static String getContent(ControlDto controlDto)
	{
		String result;
		if(controlDto.getNumberColor().equals(NumberColor.RED)) {
			result = String.format("1%03d", controlDto.getNumberContent());
		} else {
			result = String.format("2%03d", controlDto.getNumberContent());
		}
		return result;
	}
}
